'use strict';

const {formatDate} = require("../../utils/format");
module.exports = app => {
  const { STRING, INTEGER, DATE, TEXT } = app.Sequelize;

  const Product = app.model.define('Product', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    type: INTEGER,
    name: STRING(100),
    category_id: INTEGER,
    thumbnail: STRING(255),
    images: TEXT,
    sales: { type: INTEGER, defaultValue: 0 },
    status: { type: INTEGER, defaultValue: 1 },
    create_time: {
      type: DATE,
      defaultValue: new Date(),
      get() {
        return formatDate(this.getDataValue('create_time'))
      }
    },
    update_time: {
      type: DATE,
      defaultValue: new Date(),
      get() {
        return formatDate(this.getDataValue('update_time'))
      }
    },
  },{
    tableName: 'product',
    timestamps: true, // 启用时间戳(createdAt, updatedAt)
    updatedAt: 'update_time', // 不想要 updatedAt
    createdAt: 'create_time', // 想要  createdAt 但是希望名称叫做 create_time
  });

  Product.associate = function() {
    app.model.Product.belongsTo(app.model.Category, { foreignKey: 'category_id', as: 'category' });
    app.model.Product.hasMany(app.model.ProductItem, { foreignKey: 'product_id', as: 'items' });
  };

  return Product;
};
